<template>
    <div class="page-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>交易审批队列</span>
                </div>
            </template>
            <el-table :data="reviewList" v-loading="loading" style="width: 100%" empty-text="当前没有待审核的交易订单">
                <el-table-column prop="id" label="订单ID" width="100"></el-table-column>
                <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
                <el-table-column prop="type" label="交易类型" width="120">
                    <template #default="scope">
                        <el-tag :type="scope.row.type === 'BUY' ? 'danger' : 'success'">{{ scope.row.type }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" label="交易金额" width="150">
                    <template #default="scope">{{ scope.row.amount.toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip>
                    <template #default="scope">{{ new Date(scope.row.createTime).toLocaleString() }}</template>
                </el-table-column>
                <el-table-column label="操作" width="220" fixed="right">
                    <template #default="scope">
                        <el-button size="small" @click="viewDetails(scope.row.id)">查看详情</el-button>
                        <el-button size="small" type="primary" @click="handleApprove(scope.row)">批准</el-button>
                        <el-button size="small" type="danger" @click="handleReject(scope.row)">拒绝</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useAuthStore } from '@/store/auth';

const router = useRouter();
const authStore = useAuthStore();
const reviewList = ref([]);
const loading = ref(true);

// 模拟API调用
const tradeApi = {
    // 假设后端会提供一个专门获取待审批列表的接口
    getPendingOrders: () => axios.get('/api/trade/orders/pending'),
    approveTradeOrder: (orderId, approverId) => axios.post(`/api/trade/order/${orderId}/approve`, { approverId }),
    rejectTradeOrder: (orderId, approverId, reason) => axios.post(`/api/trade/order/${orderId}/reject`, { approverId, reason }),
};

const fetchReviewList = async () => {
    loading.value = true;
    try {
        const response = await tradeApi.getPendingOrders();
        reviewList.value = response.data;
    } catch (error) {
        ElMessage.error('获取待审批列表失败: ' + (error.response?.data?.message || error.message));
        reviewList.value = [];
    } finally {
        loading.value = false;
    }
};

const handleApprove = async (order) => {
    const approverId = authStore.state.user?.id;
    if (!approverId) {
        ElMessage.error('无法获取审批人ID，请重新登录。');
        return;
    }
    try {
        await tradeApi.approveTradeOrder(order.id, approverId);
        ElMessage.success(`订单 "${order.id}" 已批准`);
        fetchReviewList();
    } catch (error) {
        ElMessage.error('批准操作失败: ' + (error.response?.data?.message || error.message));
    }
};

const handleReject = (order) => {
    const approverId = authStore.state.user?.id;
    if (!approverId) {
        ElMessage.error('无法获取审批人ID，请重新登录。');
        return;
    }
    ElMessageBox.prompt('请输入拒绝原因', '拒绝订单', {
        confirmButtonText: '确认拒绝',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '拒绝原因不能为空',
    })
        .then(async ({ value }) => {
            try {
                await tradeApi.rejectTradeOrder(order.id, approverId, value);
                ElMessage.success(`订单 "${order.id}" 已被拒绝`);
                fetchReviewList();
            } catch (error) {
                ElMessage.error('拒绝操作失败: ' + (error.response?.data?.message || error.message));
            }
        })
        .catch(() => {
            ElMessage.info('已取消拒绝操作');
        });
};

const viewDetails = (id) => {
    router.push({ name: 'TradeOrderDetail', params: { id } });
}

onMounted(fetchReviewList);
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.card-header {
    font-size: 18px;
    font-weight: bold;
}
</style>